import { setToken, setUserInfo, getUserInfo } from '@/utils/auth'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { LoginForm, ProFormText } from '@ant-design/pro-components'
import { Helmet, history, useModel } from '@umijs/max'
import { message, Spin } from 'antd'
import { createStyles } from 'antd-style'
import { useRequest } from 'ahooks'
import { useEffect } from 'react'
import Settings from '../../config/defaultSettings'

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive
      }
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
      position: 'relative'
    },
    formContainer: {
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      height: '100%'
    },
    buttonGroup: {
      display: 'flex',
      justifyContent: 'space-between',
      width: '100%',
      marginTop: '16px',
    },
  }
})

const getDefaultPath = () => {
  return '/'
};

const Login: React.FC = () => {
  const { styles } = useStyles()
  const { setInitialState } = useModel('@@initialState')

  // 检查是否已登录，如果已登录则直接跳转
  useEffect(() => {
    const userInfo = getUserInfo()
    if (userInfo) {
      const urlParams = new URL(window.location.href).searchParams
      const redirect = urlParams.get('redirect')
      const defaultPath = getDefaultPath()
      history.push(redirect || defaultPath)
    }
  }, [])

  const { loading, run: runLogin } = useRequest(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    async (values: any) => {
      // 登录成功（表单校验已通过，账号为 admin，密码为 xiaobaoai）
      const mockToken = 'mock-token-' + Date.now()
      const mockUserInfo = {
        name: 'admin',
        email: 'admin',
        userCode: 'admin',
        userType: 1,
        access: 'SysAdmin',
        id: '1'
      }

      setToken(mockToken)
      setUserInfo(mockUserInfo)

      // 更新全局状态
      await setInitialState((s) => ({
        ...s,
        currentUser: mockUserInfo,
      }));

      message.success('登录成功!')

      const urlParams = new URL(window.location.href).searchParams
      const redirect = urlParams.get('redirect')

      // 判断默认重定向路径
      const defaultPath = getDefaultPath()
      history.push(redirect || defaultPath)

      return { success: true }
    },
    {
      manual: true
    }
  )

  return (
    <div className={styles.container}>
      {/* 语言切换按钮 */}
      <div style={{
        position: 'absolute',
        top: '20px',
        right: '20px',
      }}>
      </div>
      <Helmet>
        <title>
          登录 - {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >

        <Spin spinning={loading}>
          <LoginForm
            contentStyle={{
              minWidth: 280,
              maxWidth: '75vw',
            }}
            logo={<img alt="logo" src="./logo.png" />}
            title="小保AI管理后台"
            subTitle=" "
            initialValues={{
              autoLogin: true,
              email: '',
              password: ''
            }}
            onFinish={async (values) => {
              await runLogin(values)
            }}
          >
            {/* 邮箱输入框 */}
            <ProFormText
              name="email"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder="请输入你的用户名"
              rules={[
                {
                  required: true,
                  message:'请输入你的用户名!',
                },
                {
                  validator: (_, value) => {
                    if (!value || value === 'admin') {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('账号错误，请重新输入'));
                  },
                },
              ]}
            />
            {/* 密码输入框 */}
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder='请输入你的密码'
              rules={[
                {
                  required: true,
                  message:'请输入你的密码!',
                },
                {
                  validator: (_, value) => {
                    if (!value || value === 'xiaobaoai') {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('密码错误，请重新输入'));
                  },
                },
              ]}
            />
          </LoginForm>
        </Spin>
      </div>
    </div>
  )
}

export default Login
